package cn.itcast.bos.web.action.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierService;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {
	//公用调用业务层
	@Autowired
	private CourierService courierService;

	// 公用模型驱动
	private Courier courier = new Courier();

	@Override
	public Courier getModel() {
		return courier;
	}

	// 保存快递员方法
	@Action(value = "courier_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/courier.html") })
	public String courierSave() {
		courierService.save(courier);
		return SUCCESS;

	}

	// 分页显示属性驱动
	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 分页显示数据获取方法
	@Action(value = "courier_pageQuery", results = { @Result(name = "success", type = "json") })
	public String courierFindAll() {
		Pageable pageable = new PageRequest(page - 1, rows);
		// 根据条件构造Specification条件查询对象（类似hibernate的QBC查询）
		Specification<Courier> specification = new Specification<Courier>() {
			// 如果返回为null,代表无条件查询
			// Root参数获取条件表达式 如 name =?
			// CriteriaQuery获取简单查询条件返回，提供where方法
			// CriteriaBuilder 获取条件对象Predicate，复杂
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// 新建list，用来收集查询条件
				List<Predicate> list = new ArrayList<>();

				// 进行快递员工号查询
				if (StringUtils.isNotBlank(courier.getCourierNum())) {
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
					list.add(p1);
				}
				// 进行公司查询，模糊查询 company like %?%
				if (StringUtils.isNotBlank(courier.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + courier.getCompany() + ("%"));
					list.add(p2);
				}
				// 快递员类型查询，等值查询 type = ?
				if (StringUtils.isNotBlank(courier.getType())) {
					Predicate p3 = cb.like(root.get("type").as(String.class), courier.getType());
					list.add(p3);
				}
				// 多表查询（查询当前对象关联对象对应的数据表）
				// 使用Courier(Root),关联Standard
				Join<Object, Object> standardRoot = root.join("standard", JoinType.INNER);
				// 进行收派标准名称模糊查询 standard.name like %?%
				if (courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())) {
					Predicate p4 = cb.like(standardRoot.get("name").as(String.class),
							"%" + courier.getStandard().getName() + "%");
					list.add(p4);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}

		};
        //调用业务层
		Page<Courier> pageDate = courierService.findAll(specification, pageable);
		//将数据打包成前台所需的json格式
		Map<String, Object> map = new HashMap<>();
		map.put("total", pageDate.getTotalElements());
		map.put("rows", pageDate.getContent());
		ActionContext.getContext().getValueStack().push(map);

		return SUCCESS;

	}

	
	// 属性驱动
	private String ids;

	public void setIds(String ids) {
		this.ids = ids;
	}
	// 根据id快递员作废的方法
	@Action(value = "courier_delBatch", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String courierDel() {
		String[] idArray = ids.split(",");
		courierService.courierDel(idArray);
		return SUCCESS;

	}
	//查找未关联定区的快递员
	@Action(value="courier_findnoassociationfixedarea",results={@Result(name="success",type="json")})
	public String findnaassociationcourier(){
		List<Courier> coueriers = courierService.findnaassociationcourier();
		ActionContext.getContext().getValueStack().push(coueriers);
		return SUCCESS;
		
	}
	
}
